package com.tianzmp.ttq.admin.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tianzmp.ttq.admin.entity.UserInfo;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zhumengping
 */
public class JwtUtils {

    public static final String SECRET = "!@#$%^&*()ZXCVBNM";


    /**
    * <pre>
     *     生成token
    * </pre>
    * @param payLoad
    * @return java.lang.String
    * @author zhump
    * @date 2022/8/11 9:07
    */
    public static String createToken(Map<String,String> payLoad){

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);

        JWTCreator.Builder builder = JWT.create();
        payLoad.forEach(builder::withClaim);

        return builder.withAudience("admin")
                .withIssuedAt(new Date())
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));

    }

    /**
     * <pre>
     *     校验token
     * </pre>
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
    * <pre>
     *  1、解析token,获取用户id。
    * </pre>
    * @param token
    * @return java.lang.Long
    * @author zhump
    * @date 2022/8/11 11:36
    */
    public static Long getToken(String token){
        return Long.parseLong(verify(token).getClaims().get("userId").asString());
    }

}
